// import { getRouteMenusApi } from '~@/api/common/menu'
import type { UserInfo } from '~@/api/common/user'
import type { MenuData } from '~@/layouts/basic-layout/typing'
import { rootRoute } from '~@/router/constant'
import { generateFlatRoutes, generateRoutes } from '~@/router/generate-route'
// import { DYNAMIC_LOAD_WAY, DynamicLoadEnum } from '~@/utils/constant'

export const useUserStore = defineStore('user', () => {
  const routerData = shallowRef()
  const menuData = shallowRef<MenuData>([])
  const userInfo = shallowRef<UserInfo>()
  const token = useAuthorization()
  const avatar = computed(() => userInfo.value?.avatar)
  const nickname = computed(() => userInfo.value?.nickname ?? userInfo.value?.username)
  const roles = computed(() => userInfo.value?.roles)

  // const getMenuRoutes = async () => {
  //   const { data } = await getRouteMenusApi()
  //   return generateTreeRoutes(data ?? [])
  // }

  const generateDynamicRoutes = async () => {
    // 强制使用前端动态路由生成，确保仪表盘路由可用
    const { menuData: treeMenuData, routeData } = await generateRoutes()

    menuData.value = treeMenuData

    routerData.value = {
      ...rootRoute,
      children: generateFlatRoutes(routeData),
    }
    return routerData.value
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      // 获取用户信息
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        const localUserInfo = JSON.parse(userInfoStr)
        userInfo.value = {
          id: 1,
          username: localUserInfo.userName,
          nickname: localUserInfo.userName,
          avatar: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
          roles: ['USER'],
          userCompany: localUserInfo.userCompany,
          userPhone: localUserInfo.userPhone,
        }
      }
    }
    catch (e) {
      // 如果接口失败，从localStorage获取
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        const localUserInfo = JSON.parse(userInfoStr)
        userInfo.value = {
          id: 1,
          username: localUserInfo.userName,
          nickname: localUserInfo.userName,
          avatar: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
          roles: ['USER'],
          userCompany: localUserInfo.userCompany,
          userPhone: localUserInfo.userPhone,
        }
      }
    }
  }

  // 直接设置用户信息（用于登录成功后立即设置）
  const setUserInfo = (userData: any) => {
    userInfo.value = {
      id: 1,
      username: userData.userName,
      nickname: userData.userName,
      avatar: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
      roles: ['USER'],
      userCompany: userData.userCompany,
      userPhone: userData.userPhone,
    }
  }

  const logout = async () => {
    // 退出登录
    // 1. 清空用户信息
    try {
      console.log('退出登录')
    }
    finally {
      token.value = null
      userInfo.value = undefined
      routerData.value = undefined
      menuData.value = []
      // 清空localStorage中的用户信息
      localStorage.removeItem('userInfo')
    }
  }

  return {
    userInfo,
    roles,
    getUserInfo,
    setUserInfo,
    logout,
    routerData,
    menuData,
    generateDynamicRoutes,
    avatar,
    nickname,
  }
})
